﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using SqlSugar;

namespace DatabaseTool.util
{
    public class Data2Markdown
    {
        public static void data2Md(SqlSugarClient db,string dir,string schema)
        {

            using (StreamWriter sw = new StreamWriter(dir+"\\table.md"))
            {
                sw.WriteLine("## 数据库表字段说明");
                //查询所有表明及注释
                var tableDt=db.Ado.GetDataTable("SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema.tables WHERE TABLE_SCHEMA = @schema",new List<SugarParameter>(){
                    new SugarParameter("@schema",schema)
                });
                int k = 0;
                foreach (DataRow dr  in tableDt.Rows)
                {
                    sw.WriteLine("### 表"+ ++k + "-" + dr[1] + " " + dr[0] );
                    var columnDt=db.Ado.GetDataTable("SELECT column_name,column_comment,data_type FROM information_schema.COLUMNS WHERE table_name = @tableName AND table_schema = @schema",new List<SugarParameter>(){
                        new SugarParameter("@tableName",dr[0]),
                        new SugarParameter("@schema",schema)
                    });
                    sw.WriteLine("| 列名 | 类型 | 注释 |");
                    sw.WriteLine("| ----- | ----- | ------ |");
                    foreach (DataRow cdr  in columnDt.Rows)
                    {
                        sw.WriteLine("|"+cdr[0]+"|"+cdr[2]+"|"+cdr[1].ToString().Replace("\r\n","")+"|");
                    }
                }
                
            }

              
        }
        
    }
}